package thread;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
//固定线程个数的线程池
class MyThreadPool {
    private BlockingQueue<Runnable> queue = null;
    public MyThreadPool(int n) {
        //容量为1000的阻塞队列
        queue = new ArrayBlockingQueue<>(1000);
        //创建出n个线程，每个线程都不断的向阻塞队列中拿任务进行执行
        for (int i = 0; i < n; i++) {
            Thread t = new Thread(() -> {
                while (true) {
                    try {
                        Runnable r = queue.take();
                        r.run();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
            t.start();
        }
    }

    //向线程池中提交任务
    public void submit(Runnable r) throws InterruptedException {
        queue.put(r);
    }
}
public class Demo26 {
    public static void main(String[] args) throws InterruptedException {
        MyThreadPool pool = new MyThreadPool(4);
        //向线程池中提交100个任务
        for (int i = 0; i < 100; i++) {
            int id = i;
            pool.submit(() -> {
                System.out.println(Thread.currentThread().getName()+" id " + id);
            });
        }
    }
}
